<template>
  <div class="coupon">
    <!-- 面包屑导航 -->
    <div class="center-w">
      <div class="head">
        <div class="title">优惠券管理</div>
        <div class="add">
          <el-button size="small" type="success" @click="addCoupon"
            >新增优惠券</el-button
          >
          <el-input
            @input="inputSearch"
            size="small"
            v-model="inputVal"
            placeholder="请输入优惠券名称"
            style="width: 250px; "
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <div style="overflow-y: scroll;height: 100%;">
        <el-table
          border
          :header-cell-style="{
            background: '#f3f6fa',
            color: '#555'
          }"
          size="mini"
          height="78vh"
          :data="tableData"
        >
          <el-table-column type="index" align="center" label="">
          </el-table-column>
          <el-table-column
            prop="backImg"
            align="center"
            width="100"
            label="图片"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 18px; height: 18px;"
                :src="scope.row.backImg"
              >
                <div slot="error" class="image-slot">
                  <el-image :src="require('../../assets/img/lolo.png')">
                  </el-image>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            align="center"
            width="250"
            label="券名"
          ></el-table-column>
          <el-table-column
            prop="type"
            width="180"
            align="center"
            label="券类型"
          >
            <template slot-scope="scope">
              <span
                :class="scope.row.couponType == 1 ? '' : 'active'"
                style="color: brown;"
                >{{ typeList[scope.row.couponType] }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="time" align="center" label="过期时间">
            <template slot-scope="scope">
              <span v-if="scope.row.usedDay > 0">
                获得后{{ scope.row.usedDay }}天内
              </span>
              <span v-else>
                {{ scope.row.startTime + "-至-" + scope.row.endTime }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
          ></el-table-column>
          <el-table-column prop="roleName" align="center" label="优惠券开关">
            <template slot-scope="scope">
              <el-switch
                @change="updateState(scope.row)"
                v-model="scope.row.state"
              ></el-switch>
              <span style="margin-left: 10px;">
                {{ scope.row.state ? "开" : "关" }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            width="280"
            align="center"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="updateCurrentCoupon(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="warning"
                @click="giveCoupon(scope.row)"
                >赠送</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="deleteCurrentItem(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <Pagination
        v-bind:child-msg="pageparm"
        @callFather="callFather"
      ></Pagination>
    </div>

    <!-- 新增 编辑优惠券 -->
    <el-dialog
      top="5vh
    "
      :title="currentId == 1 ? '新增优惠券' : '编辑优惠券'"
      :visible.sync="addCouponShow"
      :append-to-body="true"
      width="40%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        size="small"
        ref="ruleForm"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="优惠券名：" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="优惠券图片：" prop="backImg">
          <template>
            <upload-img
              :isShowTip="false"
              :limit="1"
              :value="ruleForm.backImg"
              @input="uploadImgBack($event)"
            />
            <span style="color: red;">提示：</span>
            <span style="color: #999;"
              >默认优惠劵封面是鹏城测试logo，如需更改，请删除后重新上传。</span
            >
          </template>
        </el-form-item>

        <el-form-item label="优惠券类型：" prop="couponType">
          <el-radio-group
            :disabled="currentId != 1"
            v-model="ruleForm.couponType"
          >
            <el-radio :label="2">免费券</el-radio>
            <el-radio :label="1">现金券</el-radio>
            <el-radio :label="0">满减券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="组合项目：" v-if="ruleForm.couponType == 2">
          <el-checkbox-group
            v-model="checkedGroup"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="item in couponList"
              :key="item.commodityName"
              :label="item.commodityId"
              >{{ item.commodityName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.couponType == 1"
          label="现金券金额："
          prop="amount"
        >
          <el-input
            oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            @blur="ruleForm.amount = $event.target.value"
            v-model="ruleForm.amount"
          ></el-input>
        </el-form-item>

        <!-- 满减券 -->
        <el-form-item
          v-if="ruleForm.couponType == 0"
          label="满减金额："
          prop="amount"
        >
          <span>
            满
            <input
              oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              @blur="ruleForm.useAmount = $event.target.value"
              v-model="ruleForm.useAmount"
            />
            减
            <input
              oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              @blur="ruleForm.amount = $event.target.value"
              v-model="ruleForm.amount"
            />
          </span>
        </el-form-item>

        <el-form-item label="过期时间：" prop="startTime">
          <el-radio-group @change="checkTime" v-model="checked">
            <el-radio :label="1" style="margin-right: 10px;">
              <span>
                用户获得后
                <input
                  :disabled="checked == 2"
                  @blur="ruleForm.usedDay = $event.target.value"
                  oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
                  v-model="ruleForm.usedDay"
                />天内。</span
              >
            </el-radio>
            <div style="margin-bottom: 15px;"></div>
            <el-radio
              :label="2"
              style="margin-right: 10px;"
              :disabled="checkedGroup.length > 1"
            >
              <el-date-picker
                :disabled="checked == 1 || checkedGroup.length > 1"
                v-model="times"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="timeChage"
              >
              </el-date-picker>
            </el-radio>
          </el-radio-group>
          <div v-if="checkedGroup.length > 1">
            <span style="color: red;">提示：</span>
            <span style="color: #999;"> 组合项目大于一项无法选择时间段</span>
          </div>
        </el-form-item>

        <el-form-item
          v-if="ruleForm.couponType == 1"
          label="获得方式："
          prop="consumeAmount"
        >
          <span>
            用户消费
            <input
              oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              @blur="ruleForm.consumeAmount = $event.target.value"
              v-model="ruleForm.consumeAmount"
            />元后获得。</span
          >
        </el-form-item>

        <el-form-item label="使用限制：" prop="limitDay">
          <el-checkbox
            @change="checkDay"
            v-model="isNew"
            :disabled="checkedGroup.length > 1"
            >一天只可使用
            <input
              type="text"
              @blur="ruleForm.limitCount = $event.target.value"
              oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
              :disabled="!isNew"
              v-model="ruleForm.limitCount"
            />
            张</el-checkbox
          >
          <el-checkbox
            @change="checkAdiUse"
            v-model="ruleForm.isAdiUse"
            :disabled="checkedGroup.length > 1"
            >是否无限次数使用
          </el-checkbox>
        </el-form-item>
        <el-form-item label="是否转送：" prop="limitDay">
          <el-checkbox
            :label="2"
            v-model="ruleForm.isForwarding"
            :disabled="checkedGroup.length > 1 || ruleForm.isAdiUse"
            >可以转送。</el-checkbox
          >
          <div v-if="checkedGroup.length > 1">
            <span style="color: red;">提示：</span>
            <span style="color: #999;">组合项目大于一项会禁用使用限制</span>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCouponShow = false">取 消</el-button>
        <el-button @click="submitAuthority('ruleForm')" type="primary">{{
          currentId == 0 ? "编辑" : "新增"
        }}</el-button>
      </span>
    </el-dialog>

    <!-- 赠送优惠券 -->
    <el-dialog
      top="10%"
      title="赠送优惠劵"
      :visible.sync="giveDialogVisible"
      width="30%"
    >
      <el-form ref="giveForm" :model="giveForm" label-width="120px">
        <el-form-item label="优惠券名：">
          <span>{{ currentInfo.name }}</span>
        </el-form-item>

        <el-form-item label="赠送张数：">
          <input
            @blur="giveForm.count = $event.target.value"
            oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
            style="margin: 0;"
            v-model="giveForm.count"
          />
        </el-form-item>

        <el-form-item label="赠送对象：">
          <el-radio-group v-model="giveForm.isAllUser">
            <el-radio :label="1">全部用户</el-radio>
            <el-radio :label="0">指定用户</el-radio>
            <el-radio :label="2">标签用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!giveForm.isAllUser">
          <el-select
            v-model="giveForm.userIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入用户微信名"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in list"
              :key="item.id"
              :label="item.wxName"
              :value="item.wxid"
            >
              <div style="display:flex;justify-content:space-between">
                <el-image
                  style="width: 30px; height: 30px;"
                  :src="item.img"
                ></el-image>
                <span>{{ item.wxName }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="生成分享链接：">
          <el-button @click="generateLink" type="primary" size="mini"
            >生成链接</el-button
          >
          <div v-if="link">
            <span style="color: red; margin-right: 20px;">{{ link }}</span
            ><el-button class="copy-button" size="mini" type="danger"
              >复制</el-button
            >
          </div>
        </el-form-item> -->

        <el-descriptions
          style="padding: 0 30px;"
          v-if="giveForm.isAllUser == 2"
          :labelStyle="{ width: '80px' }"
          :column="1"
          border
        >
          <el-descriptions-item label="已选标签">
            <el-tag
              size="small"
              v-for="(item, index) in currntTagList"
              :key="item.id"
              :color="item.labelColor"
              closable
              @close="closeTags(index)"
              style="margin: 5px;"
              :style="{ borderColor: item.labelColor }"
              effect="dark"
            >
              <span> {{ item.labelName }}</span>
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标签池">
            <el-tag
              size="small"
              v-for="item in tagData"
              :key="item.id"
              :color="item.labelColor"
              style="margin: 5px;"
              :style="{ borderColor: item.labelColor }"
              @click="getTags(item)"
              effect="dark"
            >
              <span> {{ item.labelName }}</span>
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="giveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGiveUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import uploadImg from "../../components/uploadImg";

import Clipboard from "clipboard"; //复制
import {
  getCouponList,
  getCouponById,
  createCoupon,
  updateCoupon,
  delectCoupon,
  setCouponState,
  giveUserCoupon,
  getCommodityList
} from "../../api/coupon";

import { getUserList } from "../../api/user";
import { getTagList } from "../../api/tag";

export default {
  data() {
    return {
      loading: false,
      link: "",
      inputVal: "",
      isNew: false,
      currentInfo: {},
      checked: 1,
      addCouponShow: false,
      giveDialogVisible: false,
      currentId: 0,
      updateId: "",
      times: [], // 过期时间
      typeList: ["满减券", "现金券", "免费券"], //0满减 1现金 2免费
      ruleForm: {
        couponType: 2, //0满减 1现金 2免费
        name: "", //名称
        amount: 0, //券额
        useAmount: 0, //使用金额限制
        usedDay: 0, //券有效天数
        startTime: "", //券生效日期起始 /2023-04-26T06:59:53.639Z
        endTime: "", //券生效日期结束
        limitDay: 1, //使用限制-天数
        limitCount: 0, //使用限制-次数
        isForwarding: true, //可否转送
        consumeAmount: 0, //优惠券发放条件-消费金额
        state: true, //是否有效
        isAdiUse: false,
        backImg: [
          { url: "http://applet.atptest.com/RtTk5Oca1682497720771.png" }
        ],
        createBy: JSON.parse(localStorage.getItem("info")).id,
        freeItems: []
      },
      checkedGroup: [],
      couponList: [],
      giveForm: {
        isAllUser: 0,
        userIds: [],
        labelId: [],
        couponId: 0,
        count: 0
      },
      list: [],
      userList: [],
      rules: {
        name: [
          { required: true, message: "请输入优惠劵名称", trigger: "blur" }
        ],

        amount: [
          { required: true, message: "请输入现金券金额", trigger: "blur" }
        ],
        consumeAmount: [
          { required: true, message: "请输入获得方式：", trigger: "blur" }
        ],
        couponType: [
          { required: true, message: "请选择优惠券类型", trigger: "change" }
        ]
      },
      pageparm: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        searchKey: ""
      },
      tableData: [],
      tagData: [],
      currntTagList: []
    };
  },
  name: "coupon",

  components: {
    Pagination,
    uploadImg //上传图片
  },

  created() {
    this._getCouponList();
    this.getTagPageList();
  },

  mounted() {
    //复制链接
    const clipboard = new Clipboard(".copy-button", {
      text: () => this.link
    });
    clipboard.on("success", e => {
      this.$message.success("复制成功");
    });
    clipboard.on("error", e => {
      this.$message.success("复制失败");
    });
  },

  watch: {
    "giveForm.user"(val) {
      if (val == 1) {
        this.list = [];
        this.userList = [];
      }
    },
    "giveForm.isAllUser"(val) {
      if (val == 2) {
        this.giveForm.userIds = [];
      } else if (val == 0) {
        this.currntTagList = [];
      }
    }
  },

  methods: {
    //获取优惠券组合项目
    async getCommodityList() {
      const res = await getCommodityList();
      if (res.code == 200) {
        this.couponList = res.data.map(item => {
          return {
            commodityId: item.commodityId,
            commodityName: item.commodityName
          };
        });
      } else {
        this.couponList = [];
      }
    },

    // 提交赠送优惠券表单
    async submitGiveUser() {
      if (this.giveForm.count == 0) {
        return this.$message.error("赠送张数不能为0！");
      }
      if (!this.giveForm.isAllUser && this.giveForm.userIds.length == 0) {
        return this.$message.error("指定用户不能为空！");
      }
      if (this.giveForm.isAllUser == 2 && this.currntTagList.length == 0) {
        return this.$message.error("标签不能为空！");
      }
      if (this.giveForm.isAllUser == 2) {
        let tags = this.currntTagList.map(v => {
          return v.id;
        });
        this.giveForm.labelId = tags;
      }
      if (this.giveForm.isAllUser == 1) {
        this.giveForm.isAllUser = true;
      } else {
        this.giveForm.isAllUser = false;
      }
      this.giveForm.couponId = this.currentInfo.id;
      this.giveForm.count = Number(this.giveForm.count);
      let res = await giveUserCoupon(this.giveForm);
      if (res.code == 200) {
        this.$message.success("赠送成功");
        this.giveDialogVisible = false;
        this._getCouponList();
      } else {
        this.$message.error(res.message);
      }
    },

    //选择优惠券
    handleCheckedChange() {
      if (this.checkedGroup.length > 1) {
        this.checked = 1;
        this.isNew = false;
      }
      this.ruleForm.isForwarding = false;
    },

    // 用户列表模糊查询
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this._getUserList(query);
        }, 200);
      } else {
        this.options = [];
      }
    },

    // 获取标签列表
    async getTagPageList() {
      let data = {
        pageIndex: 1,
        size: 999
      };
      let result = await getTagList(data);
      if (result.code == 200 && result.data) {
        const { items } = result.data;
        this.tagData = items;
      } else {
        this.tagData = [];
      }
    },

    // 选择标签
    getTags(t) {
      let index = this.currntTagList.findIndex(v => {
        return v.id == t.id;
      });
      if (index != -1) return this.$message.warning("你已经选过该标签了!");
      this.currntTagList.push(t);
    },

    // 去除已选标签
    closeTags(e) {
      this.currntTagList.splice(e, 1);
    },

    //生成链接
    generateLink() {
      this.link = "www.baidu.com";
    },

    // 获取用户列表数据
    async _getUserList(e) {
      let data = {
        pageIndex: 1,
        size: 999,
        name: e ? e : ""
      };
      let res = await getUserList(data);
      if (res.code == 200) {
        this.list = res.data ? res.data.items : [];
      } else {
        this.$message.error(res.message);
      }
      this.loading = false;
    },

    // 赠送优惠券
    giveCoupon(r) {
      this.giveForm = {
        isAllUser: 2,
        userIds: [],
        labelId: [],
        couponId: 0,
        count: 1
      };
      this.currentInfo = r;
      this.giveDialogVisible = true;
    },

    //开关控制
    updateState(r) {
      this.$confirm(`确认${r.state ? "打开" : "关闭"}吗? `, "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          setCouponState({
            state: r.state,
            id: r.id,
            updateBy: JSON.parse(localStorage.getItem("info")).id
          }).then(res => {
            if (res.code == 200) {
              this.$message.success(`已${r.state ? "打开" : "关闭"}`);
              this._getCouponList();
            }
          });
        })
        .catch(action => {
          this.$message.info("取消操作");
          this._getCouponList();
        });
    },

    //获取方式
    checkDay(e) {
      console.log(e);
      if (!e) {
        this.ruleForm.limitCount = 0;
      } else {
        this.ruleForm.isAdiUse = false;
      }
    },

    checkAdiUse(e) {
      console.log(e);
      if (e) {
        this.ruleForm.limitCount = 0;
        this.isNew = false;
        this.ruleForm.isForwarding = false;
      }
    },

    // 选择时间
    timeChage(e) {
      this.ruleForm.startTime = this.newDate(e[0]);
      this.ruleForm.endTime = this.newDate(e[1]);
    },

    //获取详情
    async updateCurrentCoupon(id) {
      this.getCommodityList();
      this.updateId = id;
      let res = await getCouponById({ id });
      if (res.code == 200 && res.data) {
        this.currentId = 0;
        this.addCouponShow = true;
        let obj = res.data;
        for (const key in obj) {
          for (const car in this.ruleForm) {
            if (key == car) {
              this.ruleForm[car] = obj[key];
            }
          }
        }
        this.checkedGroup = obj.freeItems.map(item => {
          return item.commodityId;
        });
        if (this.ruleForm.startTime) {
          this.times = [
            new Date(this.ruleForm.startTime),
            new Date(this.ruleForm.endTime)
          ];
          this.checked = 2;
        }
        if (this.ruleForm.limitCount > 0) {
          this.isNew = true;
        }
      } else {
        this.$message.error(res.message);
      }
    },

    // 时间格式化
    newDate(time) {
      var date = new Date(time);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + m + "-" + d;
    },

    // 过期时间
    checkTime(e) {
      if (e == 2) {
        this.ruleForm.usedDay = 0;
      } else {
        this.ruleForm.endTime = "";
        this.ruleForm.startTime = "";
        this.times = [];
      }
    },

    //获取优惠券列表
    async _getCouponList() {
      const res = await getCouponList(this.pageparm);
      if (res.code == 200) {
        let { items, totalCount } = res.data;
        this.tableData = items;
        this.pageparm.total = totalCount;
      } else {
        this.$message.error(res.message);
      }
    },

    // 查询优惠券名字
    inputSearch(val) {
      this.pageparm.searchKey = val;
      this.pageparm.pageIndex = 1;
      this._getCouponList();
    },

    // 上传图片的回调
    uploadImgBack(x) {
      if (x && x.length > 0) this.ruleForm.backImg = x[0].url;
    },

    // 新增优惠券
    addCoupon() {
      this.getCommodityList();
      this.addCouponShow = true;
      this.currentId = 1;
      this.ruleForm = {
        couponType: 2, //0满减 1现金 2免费-外观
        name: "", //名称
        amount: 0, //券额
        useAmount: 0, //使用金额限制
        usedDay: 0, //券有效天数
        startTime: "", //券生效日期起始 /2023-04-26T06:59:53.639Z
        endTime: "", //券生效日期结束
        limitDay: 1, //使用限制-天数
        limitCount: 0, //使用限制-次数
        isForwarding: true, //可否转送
        consumeAmount: 0, //优惠券发放条件-消费金额
        state: true, //是否有效
        isAdiUse: false,
        backImg: [
          { url: "http://applet.atptest.com/RtTk5Oca1682497720771.png" }
        ],
        createBy: JSON.parse(localStorage.getItem("info")).id,
        freeItems: []
      };
      this.checkedGroup = [];
      if (this.$refs["ruleForm"]) {
        this.$refs["ruleForm"].resetFields();
      }
    },

    // 分页插件事件
    callFather(parm) {
      this.pageparm.pageIndex = parm.pageIndex;
      this.pageparm.pageSize = parm.size;
      this._getCouponList();
    },

    // 删除某个优惠券
    deleteCurrentItem(e) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定删除",
        cancelButtonText: "取消"
      })
        .then(() => {
          if (e.id) {
            delectCoupon({ ids: [e.id] }).then(res => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this._getCouponList();
              } else {
                this.$message.error(res.message);
                this._getCouponList();
              }
            });
          }
        })
        .catch(action => {
          this.$message.info("取消删除");
        });
    },

    //确认提交
    submitAuthority(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          if (this.ruleForm.backImg instanceof Array) {
            this.ruleForm.backImg = this.ruleForm.backImg[0].url;
          }
          this.ruleForm.limitCount = Number(this.ruleForm.limitCount);
          this.ruleForm.usedDay = Number(this.ruleForm.usedDay);
          if (this.checked == 2 && this.times.length == 0) {
            return this.$message.error("开始时间和结束时间不能为空");
          }
          if (this.isNew && this.ruleForm.limitCount == 0) {
            return this.$message.error("使用限制不能为0");
          }
          // couponType: 2, //0满减 1现金 2免费-外观
          if (this.ruleForm.couponType == 1) {
            if (this.ruleForm.amount <= 0) {
              return this.$message.error("现金券金额不能为0");
            }
            if (this.ruleForm.consumeAmount <= 0) {
              return this.$message.error("获得方式不能为0");
            }
          }
          if (this.ruleForm.couponType == 0) {
            if (this.ruleForm.useAmount <= 0 || this.ruleForm.amount <= 0) {
              return this.$message.error("满减金额两个值都不能为0");
            }
          }
          if (this.ruleForm.couponType == 2 && this.checkedGroup.length < 1) {
            return this.$message.error("免费券组合项目至少选择一项");
          }
          if (this.checked == 1 && this.ruleForm.usedDay == 0) {
            return this.$message.error("过期时间不能为0");
          }
          let proList = [];
          //组合项目
          for (let i = 0; i < this.checkedGroup.length; i++) {
            for (let j = 0; j < this.couponList.length; j++) {
              if (this.checkedGroup[i] == this.couponList[j].commodityId) {
                proList.push(this.couponList[j]);
              }
            }
          }
          this.ruleForm.freeItems = proList;
          // 新增
          if (this.currentId == 1) {
            createCoupon(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success("新增成功");
                this.addCouponShow = false;
                this._getCouponList();
              } else {
                this.$message.error(res.message);
              }
            });
          } else {
            //编辑
            this.ruleForm.id = this.updateId;
            updateCoupon(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success("编辑成功");
                this.addCouponShow = false;
                this._getCouponList();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          // alert("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 89vh;
  padding: 10px;
  border: 1px solid #ccc;
  //margin: 20px;
  .title {
    color: rgba(16, 16, 16, 1);
    font-size: 20px;
    margin-bottom: 10px;
  }

  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .active {
    color: green !important;
  }
}
.el-input {
  max-width: 300px !important;
}
input {
  text-align: center;
  border-radius: 5px;
  width: 40px;
  height: 25px;
  outline: none;
  margin: 0 10px;
  border: 1px solid #ccc;
}
</style>
